<template>
  <div class="summary-content">
    <PartitionTitle type="line" fontSize="1rem">
      <span>每日</span>
      <span class="title-sub">
        生产效率 & 产线故障率
        <span class="title-sub-active">
          - {{ queryParams.lineName }} - {{ queryParams.produceMonth }}</span
        >
      </span>
    </PartitionTitle>
    <div class="content">
      <div class="left" v-loading="chartLoading">
        <Chart
          v-if="option.xAxis.data.length > 0"
          ref="Chart"
          :option="option"
          @active-xAxis-change="handleActivexAxisChange"
        ></Chart>
        <div v-else class="no-data">暂无数据</div>
      </div>
    </div>
  </div>
</template>
<script>
import Chart from "../../components/chart";
import { getOption, colors } from "../chartOption";
import { getLastSerieData } from "../common";
import { getDayData } from "@/api/reportFormAnalysis/failureRate";
export default {
  components: { Chart },
  props: {
    queryParams: {
      type: Object,
      default: null,
    },
    // 横坐标默认选中值
    defaultxAxisActive: {
      type: String,
      default: null,
    },
  },
  data() {
    return {
      // 图表配置
      option: getOption(),
      chartLoading: false,
    };
  },
  methods: {
    async getChartData() {
      this.chartLoading = true;

      try {
        const {
          produceMonth,
          itemCategory,
          itemVariety,
          itemAppearance,
          factoryDeptName,
          lineName,
          serieData,
        } = this.queryParams;
        const params = {
          produceMonth,
          itemCategory,
          itemVariety,
          itemAppearance,
          factoryDeptName,
          lineName,
        };
        const res = await getDayData(params);
        const dataArr = res.data || [];

        let xAxisData = [];
        let seriesData1 = [];
        let seriesData2 = [];
        let standardAbnormalRatio = 0;
        for (let i = 0; i < dataArr.length; i++) {
          const ele = dataArr[i];
          xAxisData.push({
            value: ele.produceDate,
            produceDate: ele.produceDate,
            lineName: ele.lineName,
            lineCode: ele.lineCode,
            factoryDeptName: ele.factoryDeptName,
          });
          seriesData1.push({
            value: ele.produceEfficiency,
            produceDate: ele.produceDate,
            mechanEfficiencyCoef: ele.mechanEfficiencyCoef,
            lineName: ele.lineName,
            lineCode: ele.lineCode,
            factoryDeptName: ele.factoryDeptName,
            itemStyle: {
              color: ele.produceEfficiencyOk == "N" ? "red" : colors[0],
            },
            label: {
              color: ele.produceEfficiencyOk == "N" ? "red" : colors[0],
            },
          });
          seriesData2.push({
            value: ele.abnormalRatio,
            produceDate: ele.produceDate,
            lineName: ele.lineName,
            lineCode: ele.lineCode,
            factoryDeptName: ele.factoryDeptName,
            itemStyle: {
              color: ele.stoppageRatioOk == "N" ? "red" : colors[1],
            },
            label: {
              color: ele.stoppageRatioOk == "N" ? "red" : colors[1],
            },
          });
          standardAbnormalRatio =
            ele.standardAbnormalRatio || standardAbnormalRatio;
        }

        // 调整趋势图配置
        // 截断显示，只显示月-日
        this.option.xAxis.axisLabel.formatter = function (value) {
          if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
            return value.slice(5);
          }
          return value;
        };

        // 数据赋值
        this.option.xAxis.data = xAxisData;
        this.option.series[0].data = seriesData1;
        this.option.series[1].data = seriesData2;
        this.option.series[2].data = xAxisData.map(() => standardAbnormalRatio);
        this.option.series[2].markPoint.data = [
          {
            name: "",
            yAxis: standardAbnormalRatio,
            xAxis: xAxisData[xAxisData.length - 1].value,
            value: `${standardAbnormalRatio}%`,
          },
        ];
        // 折线尾部的累计
        const lastSerieData1 = getLastSerieData(seriesData1);
        if (lastSerieData1) {
          this.option.series[0].markPoint.data = [
            {
              name: "累计",
              yAxis: lastSerieData1.value,
              xAxis: lastSerieData1.produceDate,
              value: `累计: ${serieData[0].value}%`,
            },
          ];
        } else {
          this.option.series[0].markPoint.data = [];
        }
        const lastSerieData2 = getLastSerieData(seriesData2);
        if (lastSerieData2) {
          this.option.series[1].markPoint.data = [
            {
              name: "累计",
              yAxis: lastSerieData2.value,
              xAxis: lastSerieData2.produceDate,
              value: `累计: ${serieData[1].value}%`,
            },
          ];
        } else {
          this.option.series[1].markPoint.data = [];
        }
      } catch (error) {
        this.option.xAxis.data = [];
        this.option.series[0].data = [];
        this.option.series[1].data = [];
        this.option.series[0].markPoint.data = [];
        this.option.series[1].markPoint.data = [];
        console.error(error);
      }

      // 默认选中【月度】所选月份下最后一天的数据(若没到最后一天、且当天在检索时段内，则默认展示当日的前一天)
      this.$nextTick(() => {
        const xaxisdata = this.option.xAxis.data;
        if (xaxisdata?.length > 0) {
          // 判断默认选中日期
          let defaultSelectedIndex = xaxisdata.length - 1;

          if (this.defaultxAxisActive) {
            const index = xaxisdata.findIndex(
              (ele) => ele.value == this.defaultxAxisActive
            );
            if (index != -1) {
              defaultSelectedIndex = index;
            }
          } else {
            const lastDay = this.parseTime(
              new Date().getTime() - 1000 * 60 * 60 * 24,
              "{y}-{m}-{d}"
            );
            const lastDayIndex = xaxisdata.findIndex(
              (ele) => ele.value == lastDay
            );
            if (lastDayIndex != -1) {
              defaultSelectedIndex = lastDayIndex;
            }
          }

          // 默认选中
          this.$refs.Chart.handlexAxisLabelChange(
            xaxisdata[defaultSelectedIndex].value,
            defaultSelectedIndex
          );
        }
        // 关闭loading
        this.chartLoading = false;
      });
    },
    // 点击chart的横坐标（产线）
    handleActivexAxisChange(e, dataIndex) {
      // 下钻到每日
      if (e?.length) {
        this.$emit("series-line-click", e[0], [
          this.option.series[0].data[dataIndex],
          this.option.series[1].data[dataIndex],
        ]);
      }
    },
  },
  watch: {
    queryParams: {
      handler(newVal) {
        if (!newVal) {
          return;
        }
        this.getChartData();
      },
      deep: true,
    },
  },
};
</script>
<style lang="scss" scoped>
.summary-content {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;

  .content {
    width: 100%;
    flex: 1;
    position: relative;
    .left {
      width: 100%;
      height: 300px;
      border-radius: 4px;
      border: 1px solid #e9ebf1;
    }
  }
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 13px;
  color: #cccccc;
}
</style>
